#include "core/editor/code_completer.h"
#include "core/editor/code_editor.h"
#include <QRegularExpression>

CodeCompleter::CodeCompleter(CodeEditor *editor) 
    : QObject(editor), editor(editor) {
    initLanguageKeywords();
}

void CodeCompleter::initLanguageKeywords() {
    // C/C++ 关键字
    QSet<QString> cppKeywords = {
        "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor",
        "bool", "break", "case", "catch", "char", "char8_t", "char16_t", "char32_t",
        "class", "compl", "concept", "const", "consteval", "constexpr", "const_cast",
        "continue", "co_await", "co_return", "co_yield", "decltype", "default", "delete",
        "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern",
        "false", "float", "for", "friend", "goto", "if", "inline", "int", "long",
        "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator",
        "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast",
        "requires", "return", "short", "signed", "sizeof", "static", "static_assert",
        "static_cast", "struct", "switch", "template", "this", "thread_local", "throw",
        "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using",
        "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"
    };
    languageKeywords["cpp"] = cppKeywords;
    languageKeywords["c"] = cppKeywords;
    
    // Python 关键字
    QSet<QString> pythonKeywords = {
        "False", "None", "True", "and", "as", "assert", "async", "await",
        "break", "class", "continue", "def", "del", "elif", "else", "except",
        "finally", "for", "from", "global", "if", "import", "in", "is",
        "lambda", "nonlocal", "not", "or", "pass", "raise", "return",
        "try", "while", "with", "yield"
    };
    languageKeywords["python"] = pythonKeywords;
    
    // JavaScript/TypeScript 关键字
    QSet<QString> jsKeywords = {
        "abstract", "arguments", "await", "boolean", "break", "byte", "case",
        "catch", "char", "class", "const", "continue", "debugger", "default",
        "delete", "do", "double", "else", "enum", "eval", "export", "extends",
        "false", "final", "finally", "float", "for", "function", "goto", "if",
        "implements", "import", "in", "instanceof", "int", "interface", "let",
        "long", "native", "new", "null", "package", "private", "protected",
        "public", "return", "short", "static", "super", "switch", "synchronized",
        "this", "throw", "throws", "transient", "true", "try", "typeof", "var",
        "void", "volatile", "while", "with", "yield"
    };
    languageKeywords["javascript"] = jsKeywords;
    languageKeywords["typescript"] = jsKeywords;
}

void CodeCompleter::setLanguage(const QString &lang) {
    currentLanguage = lang.toLower();
}

void CodeCompleter::updateCompletionModel(const QString &code) {
    variables.clear();
    functions.clear();
    
    extractKeywords(code);
    extractFunctions(code);
    extractVariables(code);
}

void CodeCompleter::extractKeywords(const QString &code) {
    // 语言关键字已经在initLanguageKeywords中初始化
}

void CodeCompleter::extractFunctions(const QString &code) {
    QRegularExpression regex;
    
    if (currentLanguage == "python") {
        regex.setPattern("def\\s+(\\w+)\\s*\\(");
    } 
    else if (currentLanguage == "javascript" || currentLanguage == "typescript") {
        regex.setPattern("function\\s+(\\w+)\\s*\\(");
    }
    else { // C/C++
        regex.setPattern("\\w+\\s+(\\w+)\\s*\\([^)]*\\)\\s*(?:\\{|;)");
    }
    
    QRegularExpressionMatchIterator i = regex.globalMatch(code);
    while (i.hasNext()) {
        QRegularExpressionMatch match = i.next();
        functions.insert(match.captured(1));
    }
}

void CodeCompleter::extractVariables(const QString &code) {
    QRegularExpression regex;
    
    if (currentLanguage == "python") {
        regex.setPattern("\\b(\\w+)\\s*=");
    }
    else if (currentLanguage == "javascript" || currentLanguage == "typescript") {
        regex.setPattern("(?:var|let|const)\\s+(\\w+)");
    }
    else { // C/C++
        regex.setPattern("\\w+\\s+(\\w+)\\s*(?:=|;)");
    }
    
    QRegularExpressionMatchIterator i = regex.globalMatch(code);
    while (i.hasNext()) {
        QRegularExpressionMatch match = i.next();
        variables.insert(match.captured(1));
    }
}

QStringList CodeCompleter::getCompletions(const QString &prefix) const {
    QStringList completions;
    
    // 添加语言关键字
    if (languageKeywords.contains(currentLanguage)) {
        for (const QString &keyword : languageKeywords[currentLanguage]) {
            if (keyword.startsWith(prefix, Qt::CaseInsensitive)) {
                completions << keyword;
            }
        }
    }
    
    // 添加函数
    for (const QString &func : functions) {
        if (func.startsWith(prefix, Qt::CaseInsensitive)) {
            completions << func + "()";
        }
    }
    
    // 添加变量
    for (const QString &var : variables) {
        if (var.startsWith(prefix, Qt::CaseInsensitive)) {
            completions << var;
        }
    }
    
    completions.sort();
    return completions;
}